<template>
  <div class="image-uploader" @click="handleChoose()">
    <img v-show="hasFile" :src="src" :alt="alt" class="image-uploader-image">
    <mu-icon v-show="!hasFile" class="image-uploader-icon" value="add"></mu-icon>
    <input ref="input" class="image-uploader-input" type="file">
  </div>
</template>

<script>
export default {
  name: 'ImageUploader',
  data() {
    return {
      file: null
    }
  },
  computed: {
    hasFile() {
      return this.file !== null && this.file !== undefined
    },
    src() {
      return this.file ? URL.createObjectURL(this.file) : ''
    },
    alt() {
      return this.file ? this.file.name : ''
    }
  },
  mounted() {
    this.$refs.input.onchange = this.handleChange
  },
  methods: {
    handleChoose() {
      this.$refs.input.click()
    },
    handleChange() {
      this.file = this.$refs.input.files[0]
    }
  }
}
</script>

<style lang="scss">
.image-uploader {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 260px;
  height: 160px;
  padding: 5px;
  border-radius: 20px;
  border: 1px dotted #aaa;
  cursor: pointer;
}
.image-uploader .image-uploader-icon {
  font-size: 60px;
}
.image-uploader-input {
  display: none;
}
.image-uploader-image {
  width: 100%;
  height: 100%;
  object-fit: scale-down;
}
</style>
